package com.example.myapplication

import android.graphics.ColorMatrix
import android.graphics.ColorMatrixColorFilter
import android.graphics.Paint
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        filterBlueLightBtn.setOnClickListener { filterBlueLight() }
        reverseColorBtn.setOnClickListener { reverseColor() }
        resumeBtn.setOnClickListener { resumeColor() }
    }

    /**
     * 反色
     */
    private fun reverseColor() {
        val paint = Paint()
        val cm = ColorMatrix(floatArrayOf(
                -1f, 0f, 0f, 0f, 255f,
                0f, -1f, 0f, 0f, 255f,
                0f, 0f, -1f, 0f, 255f,
                0f, 0f, 0f, 1f, 0f))
        paint.colorFilter = ColorMatrixColorFilter(cm)
        window.decorView.setLayerType(View.LAYER_TYPE_HARDWARE, paint)
    }

    /**
     * 过滤蓝光
     */
    private fun filterBlueLight() {
        val paint = Paint()
        // 把蓝色减弱为原来的0.7
        val cm = ColorMatrix(floatArrayOf(
                1f, 0f, 0f, 0f, 0f,
                0f, 1f, 0f, 0f, 0f,
                0f, 0f, 0.7f, 0f, 0f,
                0f, 0f, 0f, 1f, 0f))
        paint.colorFilter = ColorMatrixColorFilter(cm)
        window.decorView.setLayerType(View.LAYER_TYPE_HARDWARE, paint)
    }

    /**
     * 恢复
     */
    private fun resumeColor() {
        window.decorView.setLayerType(View.LAYER_TYPE_HARDWARE, Paint())
    }
}